package com.lajiaomian.springbootruijiwaimai.service.impl.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.IdWorker;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.lajiaomian.springbootruijiwaimai.common.BaseContext;
import com.lajiaomian.springbootruijiwaimai.mapper.OrdersMapper;
import com.lajiaomian.springbootruijiwaimai.pojo.*;
import com.lajiaomian.springbootruijiwaimai.service.impl.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.List;
import java.util.UUID;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.stream.Collectors;

/**
 * @author lajiaomian
 * @create 2022-08-15-21:27
 */
@Service
public class OrdersServiceImpl extends ServiceImpl<OrdersMapper, Orders> implements OrdersService {
    @Autowired
    private ShoppingCartService shoppingCartService;
    @Autowired
    private OrderDetailService orderDetailService;
    @Autowired
    private UserService userService;
    @Autowired
    private AddressBookService addressBookService;

    @Override
    public Page<Orders> getPage(Integer page, Integer pageSize, String number, String beginTime, String endTime) {
        QueryWrapper wrapper = new QueryWrapper();
        //是否有name属性，有就查询
        wrapper.like(StringUtils.isNotEmpty(number),"number",number);
        boolean timeIsExist = beginTime != null && endTime != null;
        //beginTime和endTime是否都存在，有就查询
        wrapper.between(timeIsExist,"order_time",beginTime,endTime);
        //分页查询
        return page(new Page<>(page,pageSize),wrapper);
    }

    @Override
    public Page<Orders> getUserPage(Integer page, Integer pageSize,Long userId) {
        LambdaQueryWrapper<Orders> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Orders::getUserId,userId);
        return page(new Page(page, pageSize), wrapper);
    }

    @Transactional
    @Override
    public void submit(Orders orders) {

        //查询userId
        Long userId = BaseContext.getCurrId();
        //查询userName
        User user = userService.getById(userId);
        String userName = user.getName();
        //设置订单号
        long orderId = IdWorker.getId();
        //查询地址
        AddressBook addressBook = addressBookService.getById(orders.getAddressBookId());

        //设置实收金额(通过查询购物车中所有订单的amount总和)
        AtomicInteger atomic = new AtomicInteger(0);
        LambdaQueryWrapper<ShoppingCart> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(ShoppingCart::getUserId,userId);
        List<ShoppingCart> shoppingCartList = shoppingCartService.list(wrapper);
        List<OrderDetail> orderDetailList = shoppingCartList.stream().map(shoppingCart -> {
            OrderDetail orderDetail = new OrderDetail();
            orderDetail.setName(userName);//设置姓名
            orderDetail.setImage(shoppingCart.getImage()); //设置图片
            orderDetail.setOrderId(orderId);//设置订单号
            orderDetail.setDishId(shoppingCart.getDishId());//设置菜品id
            orderDetail.setSetmealId(shoppingCart.getSetmealId());//设置套餐id
            orderDetail.setDishFlavor(shoppingCart.getDishFlavor());//设置口味
            orderDetail.setNumber(shoppingCart.getNumber());//设置数量
            orderDetail.setAmount(shoppingCart.getAmount());//设置金额
            //购物车项的金额
            atomic.addAndGet(shoppingCart.getAmount().multiply(new BigDecimal(shoppingCart.getNumber())).intValue());
            return orderDetail;
        }).collect(Collectors.toList());
        //添加到订单详情表中
        orderDetailService.saveBatch(orderDetailList);
        //添加到订单表中
        orders.setNumber(String.valueOf(orderId));
        orders.setStatus(2);//设置订单状态（待配送）
        orders.setUserId(userId);//设置userId
        orders.setAmount(new BigDecimal(atomic.get()));//设置总金额
        orders.setPhone(user.getPhone());//设置手机号
        orders.setConsignee(userName);//设置收货人
        orders.setUserName(userName);//设置用户名
        orders.setOrderTime(LocalDateTime.now());//设置订单创建时间
        orders.setCheckoutTime(LocalDateTime.now());//创建付款时间
        orders.setAddress((addressBook.getProvinceName() == null ? "" : addressBook.getProvinceName())
                + (addressBook.getCityName() == null ? "" : addressBook.getCityName())
                + (addressBook.getDistrictName() == null ? "" : addressBook.getDistrictName())
                + (addressBook.getDetail() == null ? "" : addressBook.getDetail()));
        this.save(orders);
        //将购物车中的项进行删除
        shoppingCartService.removeBatchByIds(shoppingCartList);
    }
}
